//
//  Observable+Extension.swift
//  Swift_Weibo
//
//  Created by Tim on 2019/9/2.
//  Copyright © 2019 Tim. All rights reserved.
//

import Foundation
import Moya
import RxSwift
import RxCocoa

public extension Observable {
    internal func mapObject<T: Decodable>(type: T.Type, key: String) -> Observable<T> {
        return map{ result in
            guard let jsonDict = result as? [String : Any],
                let currentDict = jsonDict[key] as? [String : Any] else {
                    throw RxMoyaError.ParserError
            }
            let jsonData = try JSONSerialization.data(withJSONObject: currentDict, options: [])
            return try JSONDecoder().decode(type, from: jsonData)
        }
    }
    
    internal func mapObjects<T: Decodable>(type: T.Type, key: String) -> Observable<[T]> {
        return map{ result in
            guard let jsonDict = result as? [String : Any],
                let currentArray = jsonDict[key] as? [[String : Any]]
                else {
                    throw RxMoyaError.ParserError
            }
            let jsonData = try JSONSerialization.data(withJSONObject: currentArray, options: [])
            return try JSONDecoder().decode([T].self, from: jsonData)
        }
    }
}

enum RxMoyaError {
    case ParserError
}

extension RxMoyaError : Swift.Error {}
